package com.zrb.mobile;
 
import org.apache.http.Header;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.zrb.mobile.adapter.Project_CitylistAdapter;
import com.zrb.mobile.adapter.model.CityDto;
import com.zrb.mobile.adapter.model.CityDtos;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.ZrbRestClient;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class Project_popup_city  extends BaseActivity implements OnClickListener ,  AMapLocationListener  {

	 Project_CitylistAdapter mcitylistAdapter;
	 PopupWindow mPopupWindow;
	 ListView mPopuplist;
	 TextView mtv_areaload;
	 int curCode;
 	 String curName;
 	 private LocationManagerProxy mLocationManagerProxy;
 	// View loadingview;
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
   		this.setContentView(R.layout.popup_city_choose);
  	
   		 curName=this.getIntent().getStringExtra("name") ;
   		 curCode=this.getIntent().getIntExtra("code",0) ;
  		 initView();
  		 LoadArea();
  		 init();
	}
   
   
	
	private void initView(){
		TextView txtTitle=	(TextView)this.findViewById(R.id.titleText);
		txtTitle.setText("选择地区");
           this.findViewById(R.id.close_city_img).setOnClickListener(this);
         //  this.findViewById(R.id.tv_temp_allarea).setOnClickListener(this);
           this.findViewById(R.id.layout_arealoading).setOnClickListener(this);; 
           //loadingview= this.findViewById(R.id.loading_view);
           
           mtv_areaload=(TextView)this.findViewById(R.id.tv_areaload);
           mPopuplist=(ListView)this.findViewById(R.id.listView1);
           mPopuplist.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					// TODO Auto-generated method stub
					 CityDto curCity= mcitylistAdapter.CurrentDatas.get(arg2);
					if(null!=mcitylistAdapter) mcitylistAdapter.UpdateIndex(curCity.postcode);
 					
					 curCode=curCity.postcode;
					 curName=curCity.cityName;
					 setResult(curCode ,curName);
 				}
             });
		 
	}

	 private void LoadArea() {
			// areaApi/findCityByProvince
	 		ZrbRestClient.get("areaApi/findAllProvince", null, new AsyncHttpResponseHandler() {
				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
 
					//loadingview.setVisibility(View.GONE);
					CommonUtil.showToast("加载数据出错！", Project_popup_city.this);
				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// TODO Auto-generated method stub
					String results = new String(arg2);
					//loadingview.setVisibility(View.GONE);
					try {
						Gson gson = new Gson();
						CityDtos tmpDto = gson.fromJson(results, CityDtos.class);
						if (tmpDto.res == 1) {
							if (mcitylistAdapter == null) {
								mcitylistAdapter = new Project_CitylistAdapter(Project_popup_city.this);
								mcitylistAdapter.setSelectCode(curCode);
								mcitylistAdapter.CurrentDatas.addAll(tmpDto.data);
								CityDto tmpcityDto=new CityDto();
								tmpcityDto.postcode=0;
								tmpcityDto.cityName="全国";
								mcitylistAdapter.CurrentDatas.add(0, tmpcityDto);
								mPopuplist.setAdapter(mcitylistAdapter);
							}
						} else
							CommonUtil.showToast(tmpDto.msg,Project_popup_city.this);
					} catch (Exception e) {
						CommonUtil.showToast("加载数据出错！", Project_popup_city.this);
	 				}
				}
			});
		}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
	   switch(v.getId()){
	      case R.id.close_city_img:
	    	  this.finish();
			  overridePendingTransition(R.anim.slide_still, R.anim.slide_down_exit);
   	          break;
          case R.id.layout_arealoading:
   	          showGpsArea();
			  break;
		  case R.id.tv_temp_allarea:
			 curCode=0;
		     curName="全国";
		     setResult(curCode ,curName);
			break;
	   }
     }
	
	@Override
	public void onBackPressed(){
		
		 this.finish();
		  overridePendingTransition(R.anim.slide_still, R.anim.slide_down_exit);
	}
	
	 private void showGpsArea() {
 	 
		  if (mtv_areaload.getTag() == null) return;
		  curName=mtv_areaload.getText().toString().split(" ")[0];
		  curCode=Integer.parseInt(mtv_areaload.getTag().toString().substring(0, 2) + "0000");
		  setResult(curCode ,curName);
	}
 
	
	void setResult(int code ,String name){
         	Intent tmpIntent=new Intent();
 			tmpIntent.putExtra("name", name);
 			tmpIntent.putExtra("code", code);
 			Project_popup_city.this.setResult(Activity.RESULT_OK, tmpIntent);
 			Project_popup_city.this.finish();
 			overridePendingTransition(R.anim.slide_still, R.anim.slide_down_exit);
  		
	}
 
	/**
	 * 初始化定位
	 */
	private void init() {
		// 初始化定位，只采用网络定位
		mLocationManagerProxy = LocationManagerProxy.getInstance(Project_popup_city.this);
		mLocationManagerProxy.setGpsEnable(false);
		// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
		// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用removeUpdates()方法来取消定位请求
		// 在定位结束后，在合适的生命周期调用destroy()方法
		// 其中如果间隔时间为-1，则定位只定一次,
		// 在单次定位情况下，定位无论成功与否，都无需调用removeUpdates()方法移除请求，定位sdk内部会移除
		mLocationManagerProxy.requestLocationData(
				LocationProviderProxy.AMapNetwork, 60 * 1000, 15, this);
	}

	@Override
	public void onPause() {
		super.onPause();
		if (mLocationManagerProxy != null) {
			// 移除定位请求
			mLocationManagerProxy.removeUpdates(this);
			// 销毁定位
			mLocationManagerProxy.destroy();
		}
	} 
	 
	 @Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		// TODO Auto-generated method stub
		if (amapLocation != null && amapLocation.getAMapException().getErrorCode() == 0) {
 			 mtv_areaload.setText(amapLocation.getProvince() + " " + amapLocation.getCity());
			  mtv_areaload.setTag(amapLocation.getAdCode()); 
			
	    }
   }
}
